from typing import Optional
from xml.etree.ElementTree import Element, SubElement, tostring
from xml.dom import minidom

from src.com.itheima._script.boot.pareser._parser import RootParser


class PomXmlUtil:
    def create_pom_xml(self, group_id, artifact_id, version, packaging=None, properties=None, modules=None, dependencies=None):
        """
        动态生成 pom.xml 文件
        :param group_id: 项目 groupId
        :param artifact_id: 项目 artifactId
        :param version: 项目版本
        :param packaging: 项目打包方式
        :param properties: 属性字典，例如 {"java.version": "1.8"}
        :param modules: 模块列表，例如 ["module1", "module2"]
        :param dependencies: 依赖列表，例如 [{"groupId": "org.junit", "artifactId": "junit", "version": "4.12"}]
        :return: 格式化后的 XML 字符串
        """
        # 创建根元素
        project = Element("project", xmlns="http://maven.apache.org/POM/4.0.0")
        project.set("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
        project.set("xsi:schemaLocation", "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd")

        # 添加基本信息
        SubElement(project, "modelVersion").text = "4.0.0"
        SubElement(project, "groupId").text = group_id
        SubElement(project, "artifactId").text = artifact_id
        SubElement(project, "version").text = version
        if packaging:  # 更严谨的非空检查
            SubElement(project, "packaging").text = packaging

        # 添加 properties
        if properties:
            self.add_properties(project, properties)

        # 添加 modules
        if modules:
            self.add_modules(modules, project)

        # 添加 dependencies
        if dependencies:
            self.add_dependencies(dependencies, project)

        # 格式化 XML
        return project

    def add_dependencies(self, dependencies, project):
        deps_element = project.find("dependencies")
        if deps_element is None:
            deps_element = SubElement(project, "dependencies")
        for dep in dependencies:
            dep_element = SubElement(deps_element, "dependency")
            SubElement(dep_element, "groupId").text = dep.get("groupId")
            SubElement(dep_element, "artifactId").text = dep.get("artifactId")
            SubElement(dep_element, "version").text = dep.get("version")

    def add_modules(self, modules, project):
        modules_element = SubElement(project, "modules")
        for module in modules:
            SubElement(modules_element, "module").text = module

    def add_properties(self, project, properties):
        props_element = SubElement(project, "properties")
        for key, value in properties.items():
            SubElement(props_element, key).text = value

    def pom_str(self, project: Optional[Element] = None):
        if project is None:
            raise ValueError("project 参数不能为 None")
        rough_string = tostring(project, 'utf-8')
        parsed = minidom.parseString(rough_string)
        return parsed.toprettyxml(indent="    ")

    def save_pom_xml(self, file_path, xml_content):
        if isinstance(xml_content, Element):
            xml_content = self.pom_str(xml_content)
        try:
            with open(file_path, "w", encoding="utf-8") as f:
                f.write(xml_content)
        except Exception as e:
            raise RuntimeError(f"保存文件失败: {e}")


if __name__ == "__main__":
    this = PomXmlUtil()
    # 定义参数
    group_id = "com.itheima"
    artifact_id = "ddd-model"
    version = "1.0-SNAPSHOT"
    packaging = "pom"
    properties = {"java.version": "1.8", "project.build.sourceEncoding": "UTF-8"}
    modules = ["module1", "module2"]
    dependencies = [
        {"groupId": "org.junit", "artifactId": "junit", "version": "4.12"},
        {"groupId": "org.springframework.boot", "artifactId": "spring-boot-starter-web", "version": "2.7.0"}
    ]

    # 生成 pom.xml
    pom_xml = this.create_pom_xml(group_id, artifact_id, version, packaging, properties, modules, dependencies)
    this.add_dependencies(dependencies, pom_xml)
    # 保存到文件
    this.save_pom_xml("pom.xml", pom_xml)
